package com.chandankumar.gaejsimplesite.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.chandankumar.gaejsimplesite.gae.db.PageService;
import com.chandankumar.gaejsimplesite.model.Page;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.apache.commons.logging.Log;

@Controller
@RequestMapping(value="/page")
public class PageController {
	protected final Log logger = com.google.appengine.repackaged.org.apache.commons.logging.LogFactory.getLog(getClass());
	private UserService userService = UserServiceFactory.getUserService();
	private final String NEW_PAGE_URI = "page/new";
	
	@Autowired
	private PageService pageService;
	@RequestMapping(value="/", method=RequestMethod.GET)
	public String index(Model model){
		model.addAttribute("pages", pageService.getAll());
		return "page/index";
	}
	@RequestMapping(value="new")
	public String newPage(){
		String lameSecurityCheckUrl = lameSecurityCheck(NEW_PAGE_URI);
		return lameSecurityCheckUrl;
	}
	@RequestMapping(value="new", method=RequestMethod.POST)
	public String create(String title, String content, Long key, Model model){
		if (lameSecurityCheck()!=null){
			return lameSecurityCheck();
		}
		Page page = null;
		if(key!=null){
			page = pageService.findByKey(key);
			page.setTitle(title);
			page.setContent(content);
			page = pageService.update(page);
		} else {
			page = new Page(title, content);
			page = pageService.save(page);
		}
		
		model.addAttribute("pages", pageService.getAll());
		return "redirect:/page/";
	}
	@RequestMapping(value="/edit/{key}", method=RequestMethod.GET)
	public String edit(@PathVariable String key, Model model){
		if (lameSecurityCheck()!=null){
			return lameSecurityCheck();
		}
		Page page = pageService.findByKey(Long.valueOf(key));
		model.addAttribute("page", page);
		return NEW_PAGE_URI;
	}
	
	private String lameSecurityCheck(String destinationUrl){
		logger.debug("destination url: "+ destinationUrl);
		if(!userService.isUserLoggedIn()) {
			return "redirect:"+userService.createLoginURL("/"+destinationUrl);
		} else if (!userService.isUserAdmin()){
			return "common/403";
		}
		return destinationUrl;
	}
	private String lameSecurityCheck(){
		return lameSecurityCheck(null);
	}
}
